import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable, of } from 'rxjs';

@Injectable()
export class CacheInterceptor implements CacheInterceptor {
  constructor() {
    console.log('init :>> ');
  }
  isCached = false;
  cache: Observable<any>;
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    let query = context.getArgByIndex(0).query;
    console.log('context :>> ', context.getArgByIndex(0).query);
    console.log('context :>> ', context.getArgByIndex(0).params);
    console.log('next :>> ', next.handle.name);
    if (this.isCached) {
      console.log('isCached IF:>> ', this.isCached);
      return this.cache;
    } else {
      if (query.data) {
        this.cache = next.handle();
      }
      this.isCached = true;
      console.log('isCached ELSE:>> ', this.isCached);
    }
    next.handle().subscribe(data => {
      console.log('next.handle data :>> ', data);
    })

    return next.handle();
  }
}

